﻿jQuery(function ($) {
	//add delete button
	var deleteBtns = $('div[id="QA"] div[id="ud"]').find('input:nth-child(4)');
	if (deleteBtns) {
		deleteBtns.live('click', function (e) {
			if (confirm('Are you sure you want to delete?')) {
				var control = $(this).parents('div[id="QA"]');
				$.ajax({
					type: 'post',
					data: '{id:' + $(this).prevAll(':hidden').val() + '}',
					url: baseUrl + '/Services/QuestionService.asmx/Delete',
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function (response, success) {
						if (success === 'success') {
							control.slideUp(1000, function () {
								control.remove();
							});
							if (/\?view=\d+/.test(window.location.search)) { //if view question, redirect
								window.location.href = '/pages/Questions.aspx';
							}
						} else {
							alert('Failed to delete question.');
						}
					}
				});
			}
			e.preventDefault();
		});
	}

	//custom validation
	var input = $('#MainColumn_questionForm_titleInput');
	if (input[0]) {
		var msg = 'error';
		function showError() {
			if (!document.getElementById('error_for_title')) {
				$('<label id="error_for_title"></label>').insertAfter(input).text(msg)
				.css({
					marginLeft: '10px'
				});
			} else {
				$('#error_for_title').text(msg);
			}
		}
		//when press enter on title
		input.keydown(function (e) {
			if (e.which === 13 && input.val() === '') {
				showError();
				e.preventDefault();
			}
		});
		//when submit button is clicked
		$('#MainColumn_questionForm_submitBtn').click(function (e) {
			if (input.val() === '') {
				showError();
				e.preventDefault();
			}
		});
	}

	//rating
	$('.imgRating input').each(function () {
		var rating = $(this).parent().siblings('.lblRating').children('span'),
			currentRating = rating.text(),
			rated = false,
			uId = $('#MainColumn_userId').val();
		$(this).click(function (e) {
			e.preventDefault();
			window.a = this;
			var isAnswer = $(this).parents('div[id="AllAns"]').length !== 0,
			url = baseUrl + (isAnswer ? '/Services/AnswerService.asmx/SetRating' : '/Services/QuestionService.asmx/SetQuestionRating'),
			data = '{uID:' + uId + ',',
			selector = 'div[id="' + (isAnswer ? 'AllAns' : 'QA') + '"]';
			data += (isAnswer ? 'aID:' : 'qID:') + $(this).parents(selector).find('input:hidden').val() + '}';

			$.ajax({
				type: 'post',
				data: data,
				url: url,
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function (response, success) {
					if (success === 'success') {
						if (rated) {
							rating.text(currentRating);
						} else {
							rating.html('&#10003');
						}
						rated = !rated;
					} else {
						alert('there was an error rating the question.');
					}
				}
			});
		});
	});
});